import styles from './index.module.scss'
import Dialog from '@c/dialog'
import cm from 'classnames'
import dynamic from 'next/dynamic'
import { useEffect, useState, useRef } from 'react'
import { scoreDetail } from '@/api/score'
import dayjs from 'dayjs'
import debounce from 'lodash-es/debounce'
const ModalConvertSuccess = dynamic(() => import('../modal-convert-success'))
const Loading = dynamic(() => import('@c/request-loading'))

const Null = () => {
  return (
    <div className={styles.null}>
      <img src="/images/detail-null.webp" alt="" className={styles.img} />
      <span className={styles.span}>还没有积分记录～</span>
    </div>
  )
}

const fetchDetail = async pageNo => {
  const res = await scoreDetail({ pageNo, pageSize: 10 })
  const data = (res.data || []).map(item => {
    const time = dayjs(item.time * 1000).format('YYYY/MM/DD HH:mm')
    item.time = time
    item.type = item.change < 0 ? 'sub' : 'add'
    return item
  })
  return data
}

const Index = props => {
  const { onClose } = props
  const [succed, setSucced] = useState(false)
  const [list, setList] = useState(null)
  const scrollRef = useRef(null)
  const pre = useRef(0)
  const [page, setPage] = useState(1)
  const [isEnd, setIsEnd] = useState(false)
  const [init, setInit] = useState(false)
  const [isFetching, setFetching] = useState(false)
  const getDetail = async () => {
    const data = await fetchDetail(1)
    if (data.length < 10) {
      setIsEnd(true)
    }
    setList(data)
  }

  //下滑加载
  const handleScroll = () => {
    const total = scrollRef.current.scrollHeight - scrollRef.current.clientHeight
    const currScroll = scrollRef.current.scrollTop
    if (pre.current > currScroll) {
      return
    }
    pre.current = currScroll
    const last = total - currScroll
    if (last <= 300) {
      setPage(page => page + 1)
    }
  }

  const loadMoreData = async page => {
    setFetching(true)
    const res = await fetchDetail(page)
    if (res.length < 10) {
      setIsEnd(true)
    }
    setFetching(false)
    setList([...list, ...res])
  }

  useEffect(() => {
    setInit(true)
    const scrollListen = debounce(handleScroll, 500)
    const scrollCurrent = scrollRef?.current
    scrollCurrent?.addEventListener('scroll', scrollListen)
    getDetail()
    return () => {
      scrollCurrent?.removeEventListener('scroll', scrollListen)
    }
  }, [])

  useEffect(() => {
    if (!init || page < 2 || isEnd) {
      return
    }
    loadMoreData(page)
  }, [page])

  return (
    <>
      <Dialog className={cm(styles.content)}>
        <img loading="lazy" alt="关闭" src="/images/close.png" className={styles.close} onClick={onClose} />
        <div className={styles.titleHead}>积分明细</div>
        <div className={styles.mainContent} ref={scrollRef}>
          {list ? (
            list.length ? (
              list.map((item, index) => {
                return (
                  <div key={index} className={styles.mainItem}>
                    <span className={styles.span1}>{item.time}</span>
                    <span className={styles.span2}>{item.name}</span>
                    <span className={cm(styles.span3, item.type === 'add' ? styles.add : styles.sub)}>
                      {item.type === 'add' ? '+' : ''}
                      {item.change}
                    </span>
                  </div>
                )
              })
            ) : (
              <Null />
            )
          ) : (
            <Loading width={20} />
          )}
          {isFetching && <Loading width={14} className={styles.loadMore} />}
        </div>
      </Dialog>
      {succed && <ModalConvertSuccess onClose={() => setSucced(false)} />}
    </>
  )
}

export default Index
